package com.hdu.careerplan.util;

import com.hdu.careerplan.exception.WrongKeyInJwtException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String SIGN_KEY = "384U23EJC0-02JD";
    private static final Long EXPIRE = 172800000L * 7;

    public static String generateJWT(Map<String, Object> claims) {
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, SIGN_KEY)
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .compact();
    }

    public static Claims parseJWT(String jwt) {
        return Jwts.parser()
                .setSigningKey(SIGN_KEY)
                .parseClaimsJws(jwt)
                .getBody();

    }

    public static Object getInfoFromJWT(ServletRequest servletRequest, String attribute) throws WrongKeyInJwtException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(jwt);
        Object value = claims.get(attribute);

        if (value == null) {
            throw new WrongKeyInJwtException(attribute);
        }
        else return value;
    }

}
